package com.lanchetech.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.common.enums.CategoryLevelEnum;
import com.lanchetech.dao.CategoryMapper;
import com.lanchetech.dao.ShopCategoryMapper;
import com.lanchetech.entity.Category;
import com.lanchetech.entity.ShopCategory;
import com.lanchetech.user.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ShopCategoryMapper shopCategoryMapper;

    @Override
    public ResultData<List<Category>> findAllFrontCategoryList(Category category) {
        Boolean isUseCache = false;
        if (CategoryLevelEnum.FIRST.getLevel().equals(category.getLevel()) || new Long(11L).equals(category.getRid()) || new Long(25L).equals(category.getRid())) {
            isUseCache = true;
        }
        ValueOperations<String, List<Category>> operations = redisTemplate.opsForValue();
        String key = "CategoryList:" + DigestUtils.md5DigestAsHex((JSON.toJSONString(category)).getBytes());
        if (isUseCache) {
            List<Category> list = operations.get(key);
            if (list != null) {
                return new ResultData<>(list);
            }
        }

        List<Category> list = categoryMapper.findAllFrontCategoryList(category);
        if (isUseCache) {
            operations.set(key, list);
        }
        return new ResultData<>(list);
    }


    @Override
    public ResultData<List<ShopCategory>> getAllShopCategoryList(Long tenantId) {
        ValueOperations<String, List<ShopCategory>> operations = redisTemplate.opsForValue();
        String key = "GetAllShopCategoryList:"+tenantId;
        List<ShopCategory> result = operations.get(key);
        if (result == null) {
            result = shopCategoryMapper.findAllByTenantId(tenantId);
            operations.set(key, result);
        }
        return new ResultData<>(result);
    }

    @Override
    public ResultData getLevelTab() {
        List<Category> list = categoryMapper.getLevelTab();
        return new ResultData<>(list);
    }
}